import { createSlice } from "@reduxjs/toolkit";
import { MessageState } from "../../domain/im/entity";


const initialState: { value: any } = {
  value: {

  },
};


try {
  const messages: any = localStorage.getItem("messages");
  if (messages) {
    initialState.value = JSON.parse(messages);
  }
} catch (error) {
  console.error('Error initializing conversation state:', error);
}


export const messageSlice = createSlice({
  name: "message",
  initialState,

  reducers: {
    openMessage: (state, action) => {
      const { targetId, messages } = action.payload;
      const str = localStorage.getItem("messages")
      if (messages.length) {
        let map = str ? JSON.parse(str) : {};
        const serverMessage = messages;
        const localMessage = map[`${targetId}`] ?? [];

        const combinedMessages = [...serverMessage, ...localMessage];
        // 创建一个 Map 用于存储 fp 和对应的对象
        const uniqueMessagesByFp = new Map();

        // 遍历合并后的数组，使用 fp 作为键来去重
        combinedMessages.forEach(message => {
          if (!uniqueMessagesByFp.has(message.fp)) {
            uniqueMessagesByFp.set(message.fp, message);
          }
        });

        // 将 Map 转换成数组
        const finalMessages = Array.from(uniqueMessagesByFp.values());

        const sortedData = finalMessages.slice().sort((a: any, b: any) => {
          const timeA = new Date(a.timestamp).getTime();
          const timeB = new Date(b.timestamp).getTime();
          return timeB - timeA;
        });
        const lastMessage = sortedData.map((item) => ({
          ...item, state:
            item.state == MessageState.sending ?
              serverMessage.findIndex(((i1: any) => i1.fp == item.fp)) == -1 ? MessageState.error : MessageState.arrive : item.state
        }))


        map[`${targetId}`] = lastMessage.reverse();
        state.value = map;
        localStorage.setItem("messages", JSON.stringify(map))
        
      }

    },
    updateMessageState: (state, action) => {
      const { message } = action.payload;
      state.value = message;
      localStorage.setItem("messages", JSON.stringify(message))
    },
    updateMessageImage: (state, action) => {
      const { message } = action.payload;
      state.value = message;
      localStorage.setItem("messages", JSON.stringify(message))
    },

    deleteMessage: (state, action) => {
      const { targetId } = action.payload;


      
      const str = localStorage.getItem("messages");
      const messages  = str ? JSON.parse(str) : {};
      delete messages[`${targetId}`];
      localStorage.setItem("messages", JSON.stringify(messages))
      state.value = messages;
    },

    addMessageState: (state, action) => {
      const { targetId, message } = action.payload;
      const messages = localStorage.getItem("messages");
      if (!messages) {
        let map: any = { [`${targetId}`]: [message] }
        localStorage.setItem("messages", JSON.stringify(map))
        state.value = map;
      } else {
        let map = JSON.parse(messages);
        if (map[`${targetId}`]) {
          map[`${targetId}`] = [...map[`${targetId}`], message]
        } else {
          map[`${targetId}`] = [message];
        }
        localStorage.setItem("messages", JSON.stringify(map))
        state.value = map;

      }
    },
  },
})

export const { deleteMessage,updateMessageImage, addMessageState, updateMessageState, openMessage } = messageSlice.actions;

export default messageSlice.reducer